package com.tas.test.service;

import cn.hutool.core.util.RandomUtil;
import com.tas.test.pojo.entity.SimpleData;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author kevin
 * @Date 2022-06-21 08:51
 * @Description
 */
@Service
public class SimpleDataService {


  @Resource
  ReactiveMongoTemplate reactiveMongoTemplate;

  AtomicLong ID = new AtomicLong(0);

  @PostConstruct
  public void init(){
    Query query = new Query();
    Sort sort = Sort.by(Sort.Direction.DESC, "_id");
    query.with(sort).limit(1);
    Flux<SimpleData> simpleDataFlux = reactiveMongoTemplate.find(query, SimpleData.class);
    SimpleData maxData = simpleDataFlux.blockFirst();
    if(null != maxData){
      ID.set(maxData.getId());
    }

  }
  /**
   * 保存一条随机数据
   * @return
   */
  public Mono<SimpleData> save(){
    SimpleData simpleData = new SimpleData();
    Long id = ID.incrementAndGet();
    simpleData.setId(id);
    simpleData.setName(RandomUtil.randomString(6));
    simpleData.setContents(RandomUtil.randomString(100));
    return reactiveMongoTemplate.save(simpleData);
  }

  /**
   * 随机生成一个id，然后查询大于该id的100条记录
   * @return
   */
  public Flux<SimpleData> queryList(){
    Long randomId = RandomUtil.randomLong(1, ID.get());
    Query query = new Query();
    Criteria criteria = new Criteria();
    criteria.and("_id").gte(randomId);
    query.addCriteria(criteria);
    Sort sort = Sort.by(Sort.Direction.ASC, "_id");
    query.with(sort);
    query.limit(100);
    return reactiveMongoTemplate.find(query, SimpleData.class);
  }
}
